<template>
  <div>
    <!-- 渲染列表 -->
    <el-card>
      <el-card v-if="count == 0">暂无物品</el-card>
      <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
      <el-card v-for="(item, index) in cartList" v-if="item.goodsBuyer === name && item.goodsFlag === 0" :key="item.goodsId">
        <img class="cart-img" :src="item.goodsImg" alt="">
        <el-tag>{{ index }}</el-tag>
        <el-tag>物品:{{ item.goodsName }}</el-tag>
        <el-tag>发布者:{{ item.goodsOwner }}</el-tag>
        <el-tag>价格:{{ item.goodsPrice.toFixed (2) }} * {{ item.goodsCount }}</el-tag>
        <el-tag>数量:{{ item.goodsNum }} <el-input-number v-model="item.goodsCount " size="mini" :min="1" :max="item.goodsNum" @change="changebtn" /></el-tag>
        <el-tag>需付金额:{{ (item.goodsPrice * item.goodsCount).toFixed (2) }}元</el-tag>
        <el-button type="danger" icon="el-icon-delete" size="min" style="float: right;" @click="deleteCart(item.goodsId)" />
      </el-card>
      <el-card>
        总价: {{ priceSum.toFixed (2) }}元
        <el-tag v-if="count != 0" style="margin-left: 800px;">个人金额：{{ (()=>{
          if (userList.length === 0){return 0}
          else{return userList[0].money.toFixed (2)}
        })() }}元</el-tag>
        <el-button v-if="count !== 0 && priceSum !== 0" type="primary" style="float: right;" @click="pay">付款</el-button>
        <el-button v-else type="primary" style="float: right;" @click="nopay">付款</el-button>
      </el-card>
    </el-card>

  </div>
</template>

<script>
import cartApi from '@/api/cartManage'
import goodsApi from '@/api/goodsManage'
import userApi from '@/api/userManage'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      cartList: [],
      priceSum: 0,
      count: 0,
      userList: []
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.getAllCart()
    this.getAllGoods()
    this.getUserMoneyByUsername(this.name)
  },
  methods: {
    // 购物车为空支付失败
    nopay() {
      const h = this.$createElement

      this.$notify({
        title: '提示小助手',
        message: h('i', { style: 'color: teal' }, '购物车空空如也~赶紧添加商品到购物车吧！')
      })
    },
    pay() {
      this.$confirm(`您确认要付款吗 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.userList[0].money >= this.priceSum) {
          this.userList[0].money -= this.priceSum
          userApi.updateMoney(this.userList[0]).then(response => {
            this.$message({
              message: response.message,
              type: 'success'
            })
            this.$set(this.userList[0], 'money', this.userList[0].money)
            for (let i = 0; i < this.cartList.length; i++) {
              if (this.cartList[i].goodsBuyer === this.name) {
                goodsApi.getGoodsById(this.cartList[i].goodsId).then(response => {
                  this.$set(response.data, 'goodsFlag', 1)
                  this.$set(response.data, 'goodsBuyer', this.cartList[i].goodsBuyer)
                  this.$set(response.data, 'goodsMessage', '已付款')
                  this.$set(response.data, 'goodsCount', this.cartList[i].goodsCount)
                  goodsApi.updateGoods(response.data).then(response => {
                  })
                })
                this.$set(this.cartList[i], 'goodsFlag', 1)
                this.$set(this.cartList[i], 'goodsMessage', '已付款')
                this.$set(this.cartList[i], 'goodsCount', this.cartList[i].goodsCount)
                cartApi.updateCart(this.cartList[i]).then(response => {
                })
              }
            }
            this.priceSum = 0
            this.getAllGoods()
            setTimeout(this.handle, 2000)
          })
        } else {
          this.$message({
            type: 'warning',
            message: '你的金额不足，请充值后重试两秒后自动跳转到充值页面'
          })
          setTimeout(this.handle2, 2000)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消支付'
        })
      })
    },
    // 付款成功跳转订单查询页
    handle() {
      this.$router.push('/shopping/query')
    },
    // 金额不足跳转充值页
    handle2() {
      this.$router.push('/dashboard')
    },
    // 通过用户名获取金额
    getUserMoneyByUsername(username) {
      cartApi.getUserMoneyByUsername(username).then(response => {
        this.userList = response.data
      })
    },
    // 金额计算
    changebtn() {
      this.cartList.goodsCount += 1
      this.priceSum = 0
      this.count = 0
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].goodsBuyer === this.name && this.cartList[i].goodsFlag === 0) {
          this.count += 1
          this.priceSum += this.cartList[i].goodsPrice * this.cartList[i].goodsCount
        }
      }
    },
    deleteCart(id) {
      this.$confirm(`您确认移除该物品出购物车 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cartApi.deleteCartById(id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getAllCart()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getAllCart() {
      cartApi.getAllCart().then(response => {
        this.cartList = response.data
        this.priceSum = 0
        this.count = 0
        for (let i = 0; i < this.cartList.length; i++) {
          if (this.cartList[i].goodsBuyer === this.name && this.cartList[i].goodsFlag === 0) {
            this.count += 1
            if (this.cartList[i].goodsCount === 0) {
              this.$set(this.cartList[i], 'goodsCount', 1)
            }
            this.priceSum += this.cartList[i].goodsPrice * this.cartList[i].goodsCount
          }
        }
      })
    },
    getAllGoods() {
      goodsApi.getAllGoods().then(response => {
        this.goodsList = response.data
      })
    }
  }
}
</script>

<style>
.el-card img{
  height: 30px;
  margin-right: 10px;
}
.el-tag{
  margin-left: 10px;
}
</style>
